package com.gxgeek.springbootupgrade.drbean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @author gaoxing
 * @create 2017-12-12 下午3:06
 */
@Component
public class BeanFactoryAwareBean implements BeanFactoryAware,
        ApplicationListener<ContextRefreshedEvent> {
    private DefaultListableBeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("setBeanFactory.........................");
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("ContextRefreshed...................");

        // 注册 user 通过BeanDefinitionBuilder创建bean定义
        BeanDefinitionBuilder userBeanDefinitionBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(User.class);
        userBeanDefinitionBuilder.addPropertyValue("username", "chinfeng");
        userBeanDefinitionBuilder.addPropertyValue("password", "123456");
        beanFactory.registerBeanDefinition("user",
                userBeanDefinitionBuilder.getRawBeanDefinition());

        // 注册UserService,此属性引用已经定义的bean: user
        BeanDefinitionBuilder usersBeanDefinitionBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(UserService.class);
        usersBeanDefinitionBuilder.addPropertyReference("user", "user");
        beanFactory.registerBeanDefinition("userService",
                usersBeanDefinitionBuilder.getRawBeanDefinition());
    }
}

